package com.fingard.dsp.bank.directbank.bocom01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IContract;
import com.fingard.dsp.bank.reqrespobj.contract.*;
import com.fingard.dsp.bank.reqrespobj.contract.detail.RetAtsContractDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;

public class BOCOM01Contract extends BOCOM01Base implements IContract {
    @Override
    /**
     * 参考章节：1.1..35	收付通宝 - 协议收款子协议单笔上传（940102）
     */
    public RetAtsContract contract(ReqContract p_req) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_req.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_req.contractDetail.askNumber;

        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();//
            tr_code = BOCOM01TransType.code940102;
            writeCommonHeader(xmlWriter);
            XElement tmpXElement = new XElement("body", "");
            tmpXElement.addChild(new XElement("PtcId", p_req.contractDetail.authAgNum));
            tmpXElement.addChild(new XElement("AccName", p_req.contractDetail.payName));
            tmpXElement.addChild(new XElement("Acc", p_req.contractDetail.payAct));
            tmpXElement.addChild(new XElement("TranTyp", "0"));
            tmpXElement.addChild(new XElement("CtfTyp", convertCertTypeToBank(p_req.contractDetail.certType)));
            tmpXElement.addChild(new XElement("CtftNo", p_req.contractDetail.certNum));
            tmpXElement.addChild(new XElement("TranUpAmt", p_req.contractDetail.payAmount));
            String dayAmtLimit = p_req.contractDetail.dayAmtLimit;
            if (StringHelper.isNullOrEmpty(dayAmtLimit)) {
                dayAmtLimit = getBankConfig().getMapValueByKey("contractKeyMapping", "dayAmtLimit");
                if (StringHelper.isNullOrEmpty(dayAmtLimit)) {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = "缺失配置节点'dayAmtLimit'或值为空!";
                    retAts.writeRetDetail(tmpRetDetail);
                    return retAts;
                }
            }
            tmpXElement.addChild(new XElement("DUpAmt", dayAmtLimit));
            String monthAmtLimit = p_req.contractDetail.monthAmtLimit;
            if (StringHelper.isNullOrEmpty(monthAmtLimit)) {
                monthAmtLimit = getBankConfig().getMapValueByKey("contractKeyMapping", "monthAmtLimit");
                if (StringHelper.isNullOrEmpty(monthAmtLimit)) {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = "缺失配置节点'monthAmtLimit'或值为空!";
                    retAts.writeRetDetail(tmpRetDetail);
                    return retAts;
                }
            }
            tmpXElement.addChild(new XElement("MUpAmt", monthAmtLimit));
            tmpXElement.addChild(new XElement("MobileNo", p_req.contractDetail.cellPhone));
            tmpXElement.addChild(new XElement("Email", ""));
            tmpXElement.addChild(new XElement("EffDate", Format.Date8Format.format(new Date())));
            String deadLine = p_req.contractDetail.deadLine;
            if (StringHelper.isNullOrEmpty(deadLine)) {
                deadLine = getBankConfig().getMapValueByKey("contractKeyMapping", "deadLine");
                if (StringHelper.isNullOrEmpty(deadLine)) {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = "缺失配置节点'deadLine'或值为空!";
                    retAts.writeRetDetail(tmpRetDetail);
                    return retAts;
                }
            }
            tmpXElement.addChild(new XElement("IvdDate", deadLine));
            tmpXElement.addChild(new XElement("Rmk", p_req.contractDetail.memo));
            String periodLimit = p_req.contractDetail.periodLimit;
            if (StringHelper.isNullOrEmpty(periodLimit)) {
                periodLimit = getBankConfig().getMapValueByKey("contractKeyMapping", "periodLimit");
                if (StringHelper.isNullOrEmpty(periodLimit)) {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = "缺失配置节点'periodLimit'或值为空!";
                    retAts.writeRetDetail(tmpRetDetail);
                    return retAts;
                }
            }
            if ("1".equals(periodLimit)) {
                periodLimit = "D";
            } else if ("2".equals(periodLimit)) {
                periodLimit = "M";
            } else {
                periodLimit = "Y";
            }
            tmpXElement.addChild(new XElement("Period", periodLimit));
            tmpXElement.addChild(new XElement("AddInfo", p_req.contractDetail.sourceNoteCode));
            xmlWriter.writeXElement(tmpXElement);
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                // 解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {

                    String tmpStrParCode = tmpBkReader.getFirstText("/ap/head/particular_code");
                    String tmpStrParInfo = tmpBkReader.getFirstText("/ap/head/particular_info");

                    if (!StringHelper.isNullOrEmpty(tmpStrParCode)) {
                        tmpRetDetail.respCode = "0";
                        String errCode = tmpBkReader.getFirstText("/ap/body/ErrCode");
                        String successFlg = tmpBkReader.getFirstText("/ap/body/SuccessFlg");
                        if ("0".equals(successFlg)) {
                            tmpRetDetail.signState = ContractState.SUCCESS;
                        } else {
                            tmpRetDetail.signState = ContractState.FAIL;
                        }
                        tmpRetDetail.respInfo = tmpBkReader.getFirstText("/ap/body/ErrMsg");
                        tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", errCode);
                    } else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = tmpStrParInfo;
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsContract upContract(ReqContract p_req) throws Exception {
        return null;
    }

    @Override
    public RetAtsContract qryContract(ReqContract p_reqQry) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_reqQry.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_reqQry.contractDetail.askNumber;

        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();//
            tr_code = BOCOM01TransType.code940101;
            writeCommonHeader(xmlWriter);
            XElement tmpXElement = new XElement("body", "");
            tmpXElement.addChild(new XElement("PtcId", p_reqQry.contractDetail.authAgNum));
            tmpXElement.addChild(new XElement("StartUpdDtTm", Format.Date8Format.format(new Date())));
            String deadLine = p_reqQry.contractDetail.deadLine;
            if (StringHelper.isNullOrEmpty(deadLine)) {
                deadLine = getBankConfig().getMapValueByKey("contractKeyMapping", "deadLine");
                if (StringHelper.isNullOrEmpty(deadLine)) {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = "缺失配置节点'deadLine'或值为空!";
                    retAts.writeRetDetail(tmpRetDetail);
                    return retAts;
                }
            }
            tmpXElement.addChild(new XElement("EndUpdDtTm", deadLine));
            tmpXElement.addChild(new XElement("PayAccNo", p_reqQry.contractDetail.recAct));
            tmpXElement.addChild(new XElement("SubProtocStt", "0"));
            tmpXElement.addChild(new XElement("Offset", "0"));
            tmpXElement.addChild(new XElement("PageSize", "20"));
            xmlWriter.writeXElement(tmpXElement);
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                // 解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/head/particular_code");
                    String tmpRetMsg = tmpBkReader.getFirstText("/ap/head/particular_info");
                    if (!StringHelper.isNullOrEmpty(tmpRetCode)) {
                        if (isActiveRetCode(tmpRetCode)) {
                            String serial_record = tmpBkReader.getFirstText("/ap/body/serialRecord");
                            int FieldNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/field_num"));
                            int RecordNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/record_num"));
                            java.util.List<String[]> listStrings = DealMFSText(serial_record, '|', FieldNum, RecordNum);
                            tmpRetDetail.respCode = "0";
                            if (listStrings.size() > 0) {
                                listStrings.remove(0);
                                for (String[] strings : listStrings) {
                                    /**
                                     主协议编号(C20)|  0
                                     子协议编号(C27)|  1
                                     付款账号(C30)|  2
                                     户名(C100)|  3
                                     币种(C3)|  4
                                     证件类型(C5)|  5
                                     证件号码(C50)|  6
                                     单笔限额(N15.5)|  7
                                     日累计限额(N15.5)|  8
                                     月累计限额(N15.5)|  9
                                     手机号(C25)|  10
                                     Email（C50）|  11
                                     备注(C50)|  12
                                     协议生效日期(C8)|  13
                                     协议失效日期(C8)|  14
                                     协议状态(C1)|  15
                                     签约渠道(C1)|  16
                                     最后维护日期(C8)|  17
                                     扣费周期(C1)|  18
                                     附加信息(C100)|  19
                                     备用字段1(C100)|  20
                                     备用字段2(C100)|  21
                                     备用字段3(C100)|  22
                                     */
                                    tmpRetDetail.payAct = strings[2];
                                    tmpRetDetail.payName = strings[3];
                                    tmpRetDetail.respCode = "0";
                                    tmpRetDetail.respInfo = strings[12];
                                    if (StringHelper.isNullOrEmpty(tmpRetDetail.respInfo)) {
                                        tmpRetDetail.respInfo = strings[19];
                                    }
                                    String status = strings[15];
                                    if ("2".equals(status)) {
                                        tmpRetDetail.signState = ContractState.SUCCESS;
                                    } else {
                                        tmpRetDetail.signState = ContractState.UNSIGNED;
                                    }
                                    tmpRetDetail.signConfirmType = "1";
                                    tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", tmpRetCode);
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            } else {
                                tmpRetDetail.respCode = "-1";
                                tmpRetDetail.respInfo = tmpRetMsg;
                            }
                        } else {
                            tmpRetDetail.respCode = "-1";
                            tmpRetDetail.respInfo = tmpRetMsg;
                        }
                    } else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = "节点/ap/head/particular_code为空";
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsQryBatContract qryBatContract(ReqQryBatContract p_reqQry) throws Exception {
        return null;
    }
}
